package com.jdrx.sw.sewage.common.util;


import java.math.BigDecimal;
import java.util.Objects;

import static java.math.BigDecimal.ROUND_HALF_UP;

public class NumberUtil {

    /**
     * 精度处理
     */
    public static String precision(String val, Integer precision) {
        return precision(val, precision, null);
    }

    public static String precision(BigDecimal val, Integer precision) {
        return precision(val, precision, null);
    }

    public static String precision(String val, Integer precision, String defVal) {
        try {
            return precision(new BigDecimal(val), precision, defVal);
        } catch (Exception e) {
            return defVal;
        }
    }

    public static String precision(BigDecimal val, Integer precision, String defVal) {
        try {
            return val.setScale((precision == null ? 0 : precision), ROUND_HALF_UP).stripTrailingZeros().toPlainString();
        } catch (Exception e) {
            return defVal;
        }
    }


    /**
     * 判断String是否为数字
     */
    public static boolean judgeValue(String str) {
        String bigStr;
        try {
            bigStr = new BigDecimal(str).toString();
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 四舍五入保留三位小数
     *
     * @param data
     * @return
     */
    public static Double round_three(Double data) {
        if (Objects.isNull(data)) {
            return null;
        }
        return new BigDecimal(data).setScale(2, BigDecimal.ROUND_HALF_DOWN).doubleValue();
    }

    /**
     * 四舍五入保留精确度（samdyPao自己写了个方法哈）
     *
     * @param data
     * @return
     */
    public static Double round(Double data, int precision) {
        if (Objects.isNull(data)) {
            return null;
        }
        return new BigDecimal(data).setScale(precision, BigDecimal.ROUND_HALF_DOWN).doubleValue();
    }

}
